#include "httpdownloadfile.h"
#include "ui_httpdownloadfile.h"
#include <QFileDialog>


HttpDownloadFile::HttpDownloadFile(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HttpDownloadFile)
{
    ui->setupUi(this);
}

HttpDownloadFile::~HttpDownloadFile()
{
    delete ui;
}

void HttpDownloadFile::on_pushButton_clicked()
{
    QString filename = QFileDialog::getSaveFileName(this);
    ui->lineEdit->setText(filename);

    //设置文件路径
    file.setFileName(filename);
    //打开文件
    file.open(QIODevice::WriteOnly);



    //请求
    //获取要转换的文本
    QString text = ui->textEdit->toPlainText();
    //打开请求地址
    QString urlstr = QString("http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=6&text=%1").arg(text);

    //创建请求对象
    QUrl url(urlstr);
    QNetworkRequest request(url);
    reply = manager.get(request);  //保存应答对象指针

    //当应答对象有数据可读的时候会发送readyRead信号，还会再中途发送文件进度数据
    connect(reply,&QNetworkReply::readyRead,this,&HttpDownloadFile::read_data);
    connect(reply,&QNetworkReply::downloadProgress,this,&HttpDownloadFile::down_progress);



}
void HttpDownloadFile::read_data()
{
    QByteArray array = reply->readAll();

    qDebug()<<array.size();
    file.write(array);
}

void HttpDownloadFile::down_progress(quint64 recvsize,quint64 allsize)
{
    qDebug()<<"recv:"<<recvsize<<",   allsize:"<<allsize;

    if(recvsize == allsize)
    {
        file.close();
        disconnect(reply,&QNetworkReply::readyRead,this,&HttpDownloadFile::read_data);
        disconnect(reply,&QNetworkReply::downloadProgress,this,&HttpDownloadFile::down_progress);
    }

}
